<template>
	<!-- 新建文件夹对话框 -->
	<n-modal
		title="重命名文件"
    v-model:show="modelVisible"
    preset="dialog"
		:close-on-click-modal="false"
		width="580px"
		@close="handleDialogClose"
	>
		<n-form :model="form" :rules="formRules" ref="addFolderFormRef"
			label-width="100px"
			label-position="top"
		>
			<n-form-item label="文件夹名称" path="fileName">
				<n-input
					v-model:value ="form.fileName"
					placeholder="请输入文件夹名称"
					type="textarea"
          clearable
				></n-input>
			</n-form-item>
      <div style="display: flex; justify-content: flex-end;margin-top: 10px;" >
        <n-button @click="handleDialogClose" style="margin-right: 10px;">
          取消
        </n-button>
        <n-button type="primary" @click="handleDialogSure" :loading="sureBtnLoading">
          确定
        </n-button>
      </div>
		</n-form>
	</n-modal>
</template>

<script lang="ts" setup>
import {fileController} from '@/api/file/fileController'
import {FormItemRule,useMessage } from 'naive-ui'
import {ref} from "vue";
import Bus from '@/components/file/box/GlobalUploader/utils/bus.js'
const message = useMessage()

const addFolderFormRef = ref(null)

const modelVisible = ref(false)

const sureBtnLoading = ref(false)

const form = ref({
  fileName: ''
})

const oldName = ref('')

const userFileId =ref('')

const showRenameFileDialog = (oldName_:string,userFileId_:string) =>{
  oldName.value = oldName_
  userFileId.value = userFileId_
  form.value.fileName = oldName.value
  modelVisible.value = true
}


defineExpose({
  showRenameFileDialog
})

/**
 * 校验规则，对文件名进行校验
 */
const formRules = {
  fileName: [
    { required: true, message: '请输入文件名称', trigger: 'blur' }
  ]
}

/**
 * 取消按钮点击事件 & 对话框关闭的回调
 * @description 关闭对话框，重置表单
 */
const handleDialogClose= () => {
  // addFolderForm.value.resetFields()
  modelVisible.value = false
}


/**
 * 确定按钮点击事件
 * @description 校验表单，校验通过后调用新建文件夹接口
 */
const handleDialogSure = () => {
  sureBtnLoading.value = true
  addFolderFormRef.value?.validate((errors) => {
    if (!errors) {
      fileController.renameFile({
          fileName: form.value.fileName,
          userFileId: userFileId.value
        }).then((res) => {
          sureBtnLoading.value = false
          if (res.code === 200) {
            message.success('重命名成功')
            form.value.fileName = '';
            modelVisible.value = false
            Bus.emit('refreshFileList')
          } else {
            message.error(res.data)
          }
        }).catch(() => {
          sureBtnLoading.value = false
        })
    } else {
      sureBtnLoading.value = false
      return false
    }
  })
}



</script>
